from django_redis import get_redis_connection
from rest_framework import serializers
class RegisterSMSCodeSerializer(serializers.Serializer):
    text = serializers.CharField(max_length=4,min_length=4,required=True,label='用户输入的图形验证码')
    image_code_id = serializers.UUIDField(required=True,label='uuid')

    """
    序列化器的验证分为4种方式:
        1.类型验证
        2.选项
        3.单个字段
        4.多个字段
    """

    def validate(self, attrs):
        # 1.获取用户输入的
        text = attrs.get('text')
        # 2.获取redis的
        image_code_id = attrs.get('image_code_id')
        # 3.比对
        redis_conn = get_redis_connection('code')
        redis_text = redis_conn.get('img_%s' % image_code_id)
        # redis的数据是有时效的
        if redis_text is None:
            raise serializers.ValidationError('图片验证码已经过期')
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError('图片验证码不一致')
        return attrs